<template>
  <div class="page-container">
    <el-container>
      <el-aside width="280px" class="page-aside" v-drag v-collapse>
        <div class="tree-box">
          <el-row>
            <el-input
              placeholder="搜索"
              v-model="filterText"
              style="margin-right: 10px"
              clearable
            />
          </el-row>
          <el-row class="page-aside-grow">
            <el-tree
              style="width: 100%"
              v-loading="loadTree"
              element-loading-text="数据加载中..."
              ref="tree"
              node-key="id"
              class="filter-tree"
              :data="treeData"
              :props="treeProps"
              :highlight-current="true"
              :default-expanded-keys="treeExpand"
              :expand-on-click-node="true"
              :filter-node-method="filterNode"
              @node-click="nodeClick"
            >
              <template v-slot="{ data }">
                <div class="node-item">
                  <span class="node-label" :title="data.text"><span>{{data.text}}</span></span>
                </div>
              </template>
            </el-tree>
          </el-row>
        </div>
      </el-aside>
      <el-main class="page-main">
        <!--表格内容栏-->
        <ac-table
          ref="dataTable"
          pkName="id"
          :filters="filters"
          :filterFields="filterFields"
          :columns="columns"
          :checkRowOpShow="checkRowOpShow"
          @handleTableOperator="handleTableOperator"
          @handleCellOperator="handleCellOperator"
        ></ac-table>
      </el-main>
    </el-container>

    <!--新增编辑界面-->
    <el-dialog
      :title="operator"
      width="800px"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <ac-form
        ref="dataForm"
        v-model="formData"
        :fields="columns"
        :rules="rules"
        :disabled="!dialogEdit"
      />
      <template #footer>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible = false"
        >取消</el-button>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
        <el-button
          v-if="!dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible = false"
        >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getOrganization, clearEmployee } from '@/utils/system';
import api from '@/http/api';

const roles = ref({});
const filters = ref({
  code: '',
  name: '',
  status: '',
  organizationId: '',
  roleNames: '',
  valid: ''
});
const filterFields = ref([
  {prop: "name", label: "姓名/账号/角色"},
  {prop: "valid", label: "是否有效", type: "dict-select", dictCode: "dictYesNo"}
]);
const columns = ref([
  {prop: "name", label: "姓名", minWidth: 90, click: true},
  {prop: "sex", label: "性别", minWidth: 80, type: 'dict-radio', dictCode: 'dictSex'},
  {prop: "username", label: "登录账号", minWidth: 110},
  {prop: "password", label: "登录密码", minWidth: 110, type: 'password', table: false, placeholder: (data) => {
      return dialogEdit.value && (data.id || '') !== '' ? '密码为空时不修改密码' : '';
    }
  },
  {prop: "organizationId", label: "默认部门", minWidth: 140, type: 'organization'},
  {prop: "belongIds", label: "归属部门", minWidth: 140, table: false, type: 'organization', leafSelect: false, multiple: true, appendToBody: true},
  {prop: "roleIds", label: "所属角色", sortable: false, minWidth: 110, colspan: 2, type: 'checkbox', options: () => {
      return roles.value;
    }
  },
  {prop: "ordinal", label: "排序", width: 90, type: 'number'},
  {prop: "valid", label: "是否有效", width: 100, type: 'dict-radio', dictCode: "dictYesNo"},
  {prop: "updateTime", label: "更新时间", minWidth: 160, onlyShow: true, type: "datetime"},
  {prop: "createTime", label: "创建时间", minWidth: 160, onlyShow: true, table: false, type: "datetime"},
]);
const operator = ref('');
const dialogVisible = ref(false);
const dialogEdit = ref(true);
const editLoading = ref(false);
const rules = ref({
  name: [{required: true, message: "请输入姓名", trigger: "blur"}],
  valid: [{required: true, message: "请选择是否有效", trigger: "change"}],
  organizationId: [{required: true, message: "请选择默认部门", trigger: "change"}],
});
const formData = ref({ roleIds: '' });
const dataTable = ref();
const dataForm = ref();

const filterText = ref('');
const loadTree = ref(false);
const treeData = ref([]);
const treeProps = ref({
  children: 'children',
  label: 'text'
});
const treeExpand = ref(['0']);
const tree = ref();
const currNode = ref(null);

const filterNode = (value, data) => {
  if (!value) return true;
  return data.text.indexOf(value) >= 0
    || (data.data != null && data.data.code != null && data.data.code.indexOf(value) >= 0);
};

const checkRowOpShow = (op, row) => {
  return !(op.name === "删除" && (row.username || '') !== '');
};

const nodeClick = (data, treeNode) => {
  if (currNode.value && currNode.value.id === data.id) {
    treeNode.checked = !treeNode.checked;
  } else {
    treeNode.checked = true;
  }

  if (treeNode.checked) {
    currNode.value = data;
    filters.value.organizationId = data.id || '';
    dataTable.value.refreshPage(1);
  } else {
    tree.value.setCurrentKey(null);
    currNode.value = null;
    filters.value.organizationId = '';
    dataTable.value.refreshPage(1);
  }
};

const handleCellOperator = (property, value, row) => {
  formData.value = Object.assign({}, row);
  dialogVisible.value = true;
  dialogEdit.value = false;
  operator.value = "查看";

  editLoading.value = true;
  api.post("/system/employee/queryBy", { id: row.id }).then((res) => {
    formData.value = Object.assign({}, res.data);
    nextTick(() => {
      dataForm.value && dataForm.value.clearValidate();
    });
    editLoading.value = false;
  });

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const handleTableOperator = (button, row) => {
  if (button.buttonType === "edit") {
    editLoading.value = true;
    api.post(button.dataSourUrl, { id: row.id }).then((res) => {
      formData.value = Object.assign({}, res.data, { button: button });
      if (formData.value.organizationIds) {
        formData.value.belongIds = formData.value.organizationIds.join(',')
      }

      operator.value = button.name;
      dialogVisible.value = true;
      dialogEdit.value = true;
      nextTick(() => {
        dataForm.value && dataForm.value.clearValidate();
      });
      editLoading.value = false;
    });
  } else if (button.buttonType === "add") {
    formData.value = {
      roleIds: '',
      button: button,
      organizationId: filters.value.organizationId,
      valid: '1'
    };

    operator.value = button.name;
    dialogVisible.value = true;
    dialogEdit.value = true;
    nextTick(() => {
      dataForm.value && dataForm.value.clearValidate();
    });
  } else {
    formData.value = { roleIds: '', button: button, valid: '1' };
    operator.value = button.name;
    dialogVisible.value = true;
    dialogEdit.value = true;
    nextTick(() => {
      dataForm.value && dataForm.value.clearValidate();
    });
  }
};

const loadRoles = async () => {
  await api.post("/system/role/queryList", {}).then((res) => {
    const roleOptions = [];
    if (res.data && res.data.length > 0) {
      res.data.forEach(data => {
        roleOptions.push({key: data.id, value: data.name});
      });
    }
    roles.value = roleOptions;
  });
};

const submitForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm("请确认是否提交？", "提示", { type: "info" }).then(() => {
        editLoading.value = true;
        if (formData.value.belongIds) {
          formData.value.organizationIds = formData.value.belongIds.split(',')
        }
        api.post(formData.value.button.dataDestUrl, formData.value)
          .then((res) => {
            ElMessage.success(res.message);
            dialogVisible.value = false;
            dataTable.value.findPage();
            editLoading.value = false;
            clearEmployee();
          }).catch(() => {
          editLoading.value = false;
        });
      }).catch(() => {});
    } else {
      ElMessage.error("数据录入不正确，请重新检查！");
    }
  });
};

const loadOrganization = async(id) => {
  loadTree.value = true
  treeData.value = await getOrganization();
  treeExpand.value = [treeData.value && treeData.value[0] && treeData.value[0].id, id || '0'];
  loadTree.value = false
};

watch(() => filterText.value, (val) => {
  tree.value.filter(val);
});

onMounted(() => {
  loadRoles();
  loadOrganization();
});
</script>

<style lang="scss" scoped>
.page-aside-grow {
  .node-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 100%;

    .node-label {
      flex-grow: 1;
      width: 1px;
      text-overflow: ellipsis;
      overflow: hidden;
      display: flex;

      > span {
        width: 100%;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
}
:deep(.el-tree-node:not(.is-current):focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content:hover) {
  background-color: #f5f7fa!important;
}
:deep(.el-tree-node.is-current:focus>.el-tree-node__content) {
  background-color: #ecf5ff!important;
}
.tree-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>